package cn.com.callback;

import groovy.json.*;
import groovy.swing.impl.DefaultAction;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.RequestDispatcher;
import cn.com.elite.EliteBean;
import java.security.MessageDigest;
import java.sql.ResultSet;
import java.text.SimpleDateFormat;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import com.wisdge.dataservice.Result;
import java.util.Map;
import java.util.Date;
import java.util.HashMap;
import org.json.JSONObject;
import org.json.JSONArray;
import org.json.JSONException;
import cn.com.elite.Util;
import cn.com.kh.KHUtil

/**
 *
 * @Title: api_rm_statisfaction
 * @Description:深圳水务提供avaya传递IVR按键操作历史轨迹--外部接口
 * @author: qah
 * @date 2020-07-27 10:20:00
 *
 */

public class api_sw_keyinfo implements ServiceBackInvoke {
    private static final Log log = LogFactory.getLog(api_sw_keyinfo.class);

    public String doCallBack(EliteBean eliteBean, HttpServletRequest request, HttpServletResponse response) {

        response.setCharacterEncoding("UTF-8");
        request.setCharacterEncoding("utf-8");

        log.debug("-------------------------start api_rm_statisfaction 获取avayaIVR按键操作历史轨迹开始-----------------");
        log.debug("request请求----------------:" + request);

        String getMethod = request.getMethod();
        String callJson = "";
        BufferedReader iny = null;

        log.debug("getMethod:" + getMethod);
        if (getMethod.equals("GET")) {
            callJson = request.getParameter("jsondata");
        } else {
            InputStreamReader reader = new InputStreamReader(request.getInputStream(), "UTF-8");
            iny = new BufferedReader(reader);
            String line;
            while ((line = iny.readLine()) != null) {
                callJson += line;
            }
        }

        log.debug("callJson:" + callJson);

        String sys_source = "";
        String arr_data = "";
        try {
            // 调用处理信息
            JSONObject inObject = new JSONObject(callJson);
            log.debug("处理前的Json：" + inObject.toString());

            sys_source = KHUtil.GetJV(inObject, "sys_source");
            arr_data = KHUtil.GetJV(inObject, "data");

            log.debug("解析信息-sys_source：" + sys_source + " arr_data：" + arr_data);
            if (sys_source != 'AVAYA') {
                return "{\"resultcode\":\"-1\",\"resultmessage\":\"调用接口返回异常，请检查报文格式！\",\"data\":null}";
            }
        } catch (Exception e) {
            log.error("接口处理异常" + e.getMessage());
            // 失败返回
            return "{\"resultcode\":\"0\",\"resultmessage\":\"处理失败(" + e.getMessage() + ")\",\"data\":[]}";

        }
        // 调用处理信息
        long startTime = System.currentTimeMillis();
        JSONArray arrJsonArray;
        Map<String, String> dealMap = new HashMap<String, String>();
        Map<String, String> dealMsgMap = new HashMap<String, String>();
        JSONArray resArray = new JSONArray();
        String reJson = null;
        arrJsonArray = new JSONArray(arr_data);

        try {
            int arrInt = arrJsonArray.length();
            log.debug("接入List数量:" + arrInt);

            for (int i = 0; i < arrInt; i++) {
                JSONObject arrsfJson = arrJsonArray.getJSONObject(i);

                //按键轨迹信息
                String recguid = KHUtil.GetJV(arrsfJson, "recguid");
                String flowid = KHUtil.GetJV(arrsfJson, "flowid");
                String nodeid = KHUtil.GetJV(arrsfJson, "nodeid");
                String starttime = KHUtil.GetJV(arrsfJson, "starttime");
                String endtime = KHUtil.GetJV(arrsfJson, "endtime");
                String areatype = KHUtil.GetJV(arrsfJson, "areatype");
                log.debug("解析信息-recguid：" + recguid + " flowid：" + flowid + " nodeid：" + nodeid + " starttime：" + starttime + " endtime：" + endtime + " areatype：" + areatype);

                //处理
                String dealResult = "";
                String dealMessage = "";
                if (KHUtil.isNull(recguid) || KHUtil.isNull(flowid) || KHUtil.isNull(nodeid) || KHUtil.isNull(starttime) || KHUtil.isNull(endtime)) {
                    dealResult = "0";
                    dealMessage = KHUtil.isNullMSG("recguid", recguid) + KHUtil.isNullMSG("flowid", flowid) + KHUtil.isNullMSG("nodeid", nodeid) + KHUtil.isNullMSG("starttime", starttime) + KHUtil.isNullMSG("endtime", endtime);
                } else {
                    try {
                        //判断推送数据是否重复
                        def orderno;
                        def selectordernoresult = eliteBean.chaxun_sql("Select Max(Orderno) + 1 As Orderno From Szwg_Ivr_Keyinfo Where Recguid = '" + recguid + "'", "dataSource");
                        if (selectordernoresult.size() > 0) {
                            orderno = selectordernoresult.get(0).get("Orderno");
                            if (orderno == null) {
                                orderno = 1;
                            }
                        } else {
                            orderno = 1;
                        }

                        //判断最新一条写入就是1
                        String insertSQL = "Insert Into Szwg_Ivr_Keyinfo (Recguid, Flowid, Nodeid, Starttime, Endtime, Areatype, Createdtime, Orderno, Finalno) Values ('" + recguid + "', '" + flowid + "', '" + nodeid + "', '" + starttime + "', '" + endtime + "', '" + areatype + "', Getdate(), '" + orderno + "', 1)";
                        eliteBean.update(insertSQL, "dataSource");

                        //初始化更新 当前uuid全部为0
                        String dataFixSQL = '''Update Szwg_Ivr_Keyinfo
                                                   Set Szwg_Ivr_Keyinfo.Finalno = Case
                                                                                    When Szwg_Ivr_Keyinfo.Createdtime = Szwg_Ivr_Keyinfo_Finalno.Max_Createdtime Then
                                                                                     1
                                                                                    Else
                                                                                     0
                                                                                  End From (Select Recguid, Max(Createdtime) As Max_Createdtime
                                                                                              From Szwg_Ivr_Keyinfo R1
                                                                                             Where Createdtime >= Dateadd(Day, -1, Getdate())
                                                                                               And R1.Recguid = \'''' + recguid + '''\'
                                                                                               And R1.Finalno = 1
                                                                                               And Len(Areatype) > 0
                                                                                             Group By Recguid) As Szwg_Ivr_Keyinfo_Finalno
                                                 Where Szwg_Ivr_Keyinfo.Recguid = \'''' + recguid + '''\'
                                                   And Szwg_Ivr_Keyinfo.Recguid = Szwg_Ivr_Keyinfo_Finalno.Recguid
                                                   And Szwg_Ivr_Keyinfo.Createdtime >= Dateadd(Hour, -3, Getdate())
                                                   And Len(Szwg_Ivr_Keyinfo.Areatype) > 0
                                                   And Szwg_Ivr_Keyinfo.Finalno = 1''';
                        eliteBean.update(dataFixSQL, "dataSource");

                    } catch (Exception e) {
                        dealResult = "0";
                        dealMessage = "当前案件轨迹信息执行更新结果SQL异常";
                        log.error(dealMessage + ":" + e.getMessage());
                    }
                }

                log.debug("当前REC_GUID:" + recguid + " 处理结果Code:" + dealResult + " 处理结果Message:" + dealMessage);
                dealMap.put(recguid, dealResult);
                dealMsgMap.put(recguid, dealMessage);
            }
            int j = 0;
            for (Map.Entry<String, String> m : dealMap.entrySet()) {
                JSONObject resObject = new JSONObject();
                resObject.put("id", m.getKey());
                resObject.put("code", "1");
                resArray.put(j, resObject);
                j++;
            }

            // 包装拼接返回JSONObject
            reJson = "{\"resultcode\":\"1\",\"resultmessage\":\"处理完成、调用问题处理时长(毫秒):" + (System.currentTimeMillis() - startTime) + "\",\"data\":" + resArray.toString() + "}";
            log.debug("返回Json:" + reJson);
            return reJson;
        } catch (JSONException e) {
            reJson = "{\"resultcode\":\"0\",\"resultmessage\":\"处理失败(" + e.getMessage() + "),调用问题处理时长(毫秒):" + (System.currentTimeMillis() - startTime) + "\",\"data\":[]}";
            log.debug("处理异常返回Json:" + reJson);
            return reJson;
        }

    }
}
